<?php

require_once 'common.php';

$action =$_REQUEST['action'];

$ob = new wechart_class();

$wx = new wechat_class();



$nav=array('微信设置',9,26);

if ($action == '') {

	$do_action = $_POST['do_action'];

	

	if($do_action=='wechat.menu'){

		    $_where = $_data = array();

		    $mid=$_POST['mid'];

			$_data['menu_name']= $_POST['menu_name'];

			$_data['parent_id']= $_POST['parent_id'];

			$_data['replay_type']= $_POST['replay_type'];

			$_data['contents_txt']= $_POST['contents_txt'];

			$_data['contents_img']= $_POST['contents_img'];

			$_data['contents_link']= $_POST['contents_link'];

			if(empty($mid)) {

				if($_data['parent_id']) {

					//二级菜单不允许超过5个

					$_count =$ob->model('wechart')->get_childnum_by_id($_data['parent_id']);

					if($_count >= 5) {

						$_return = array();

						$_return['status'] = 0;

						$_return['msg'] = '二级菜单不允许超过5个';

						echo json_encode($_return);

						exit;

					}

				} else {

					//一级菜单不允许超过3个

					$_count = $ob->model('wechart')->get_parentnum_by_id();

					if($_count >= 3) {

						$_return = array();

						$_return['status'] = 0;

						$_return['msg'] = '一级菜单不允许超过3个';

						echo json_encode($_return);

						exit;

					}

				}

				$_data['time_add'] = time();

				$ob->insert('weixin_menu', $_data);

			} else {

				$ob->update('weixin_menu', $_data,'id='.$mid);

			}

			$_return = array();

			$_return['status'] = 1;

			$_return['msg'] = '';

		  echo json_encode($_return);

		  exit;

	} else if($do_action == 'wechat.menu_order') {	  

		  $sort_order= $_POST['sort_order'];

		  $id_array=explode("|",$sort_order);

		 

		   foreach($id_array as $k=>$i){

			   $_data['order_id']=$k;

			   $ob->update('weixin_menu', $_data,'id='.$i);

		   }

		    $_return = array();

			$_return['status'] = 1;

			$_return['msg'] = '';

		    echo json_encode($_return);

		    exit;

	} else if($do_action == 'wechat.menu_publish') {

            //把菜单同步到服务号的菜单上

            //所有的菜单列表

            $newmenu = $_whereAll = $_order = array();

            $resAllMenu = $ob->fetch_all('weixin_menu',$limit,$offset,$cons,'order by order_id asc,id desc');;

            $newmenu['button'] = array();

            $jj = 0;

            if(count($resAllMenu)) {

                foreach($resAllMenu as $k => $v) {

                    if($v['parent_id'] == 0) {

                        if($v['replay_type'] < 3) {

                            $newmenu['button'][$jj] = array(

                                'type'=>'click', 'name'=>$v['menu_name'], 'key'=>$v['id']

                            );

                        } else {

                            $newmenu['button'][$jj] = array(

                                'type'=>'view', 'name'=>$v['menu_name'], 'url'=>''.$v['contents_link']

                            );

                        }

                        $ii = 0;

                        foreach($resAllMenu as $kk=>$vv) {

                            if($vv['parent_id'] > 0 && $vv['parent_id'] == $v['id']) {

                                unset($newmenu['button'][$jj]['type']);

                                unset($newmenu['button'][$jj]['key']);

                                if($vv['replay_type'] < 3) {

                                    $newmenu['button'][$jj]['sub_button'][$ii] = array(

                                        'type'=>'click', 'name'=>$vv['menu_name'], 'key'=>$vv['id']

                                    );

                                } else {

                                    $newmenu['button'][$jj]['sub_button'][$ii] = array(

                                        'type'=>'view', 'name'=>$vv['menu_name'], 'url'=>''.$vv['contents_link']

                                    );

                                }

                                $ii++;

                            }

                        }

                        $jj++;

                    }

                }

            }

            $set_option=$ob->fetch_one('weixin_config','id=1','*');

			

			$options = array(

				'token'=>  $wx->getAccessToken(),

				'appid'=> $set_option['wx_appid'],

				'appsecret'=> $set_option['wx_appsecret'],

			);
            file_put_contents("bcd.json", json_encode($options));
			
            require_once WY_ROOT .'/includes/libs/Weixin/wechat.php';
			$weObj = new Wechat($options);
			if($newmenu) {
				$result = $weObj->createMenu($newmenu);
			} else {
				$result = $weObj->deleteMenu();
			}

            if($result == true) {

                $_return['status'] = 1;

                $_return['msg'] = '';

            } else {

                $_return['status'] = 0;

                $_return['msg'] = $result;

            }

            echo json_encode($_return);

            exit;

    }

	

	$id= _G("mid",'int');

	

	if($id){

			$menuinfo=$ob->model('wechart')->get_menuinfo_by_id($id);

	}else{

			$menuinfo=array(

			"id"=>'',

			"menu_name"=>'',

			"parent_id"=>'',

			"replay_type"=>'',

			"contents_txt"=>'',

			"contents_img"=>'',

			"contents_link"=>'',

			"time_add"=>'',

			"order_id"=>'',

			);

	}

	$menu = $ob->model('wechart')->get_list();

	$materialurl=$ob->model('wechart')->get_materialurl();

	

	$resUrl = $ob->getSelectHtml(1, $attention_info['contents_img']);

    require View::getView('header');

    require View::getView('wechart');

    require View::getView('footer');

    View::Output();

}

//微信接口配置

if ($action =='subscribe') {

	$do_action = $_REQUEST['do_action'];

	$attention_info =$ob->fetch_one('user_attention','keywords=""','*'); 

	if($do_action=="wechat.subscribe_set"){

		$_where_save = $_data = array();

		$_data =$_POST;

		unset($_data['do_action']);

		if(empty($_data['keywords_any'])) {

			$_data['keywords_any']=0;

		}

		if($attention_info) {

			$ob->update('user_attention', $_data,'id='.$attention_info['id']);	

		} else {

			$ob->insert('user_attention', $_data);

		}

		Redirect('/empress/wechart.php?action=subscribe');

	}

	

	$resUrl = $ob->getSelectHtml(1, $attention_info['contents_img']);

	

    require View::getView('header');

    require View::getView('subscribe');

    require View::getView('footer');

    View::Output();

}



//微信接口配置

if ($action =='set_token') {

	$do_action = $_REQUEST['do_action'];

	if($do_action=="token_unbind"){

	  $unbind_data['is_binding']=0;

	  $ob->update('weixin_config', $unbind_data,'id=1');	

	}else if($do_action=="wechat.token_set"){

	   $_data['wx_uname'] = $_POST['wx_uname'];

       $_data['wx_pwd'] = $_POST['wx_pwd'];

	   $_data['wx_appid'] = $_POST['wx_appid'];

	   $_data['wx_appsecret'] = $_POST['wx_appsecret'];

       $_data['is_binding'] = 1;

	   $ob->update('weixin_config', $_data,'id=1');	

	   $_return['status'] = 1;

       $_return['msg'] = '';

       echo json_encode($_return);

       exit;

	}

	$weixin_config=$ob->fetch_one('weixin_config','id=1','*');

    require View::getView('header');

    require View::getView('set_token');

    require View::getView('footer');

    View::Output();

}

if($action=="material"){
	$do_action = $_REQUEST['do_action'];
	$type =  $_REQUEST['type'];
	$d =  $_REQUEST['d'];
	
    if($_POST) {
            if($do_action == 'action.file_upload') {
                //上传标题图片
				    $file = $_FILES['Filedata'];
					$file_size = $file['size'];
					
					if ($file_size <= 0 || $file_size > 300000) {
						$msg = '上传的文件最大支持300KB';
						$_return = array();
						$_return['status'] =2;
						$_return['msg'] =$msg;
						echo json_encode($_return);
						exit;
					}
					$file_error = $file['error'];
					$file_tmp = $file['tmp_name'];
					if ($file_error <> 0) {
						$msg = '上传出现意外错误，请稍候重试...';
						$_return = array();
						$_return['status'] =2;
						$_return['msg'] =$msg;
						echo json_encode($_return);
						exit;
					}
			
        
                $filename = explode('.',$file['name']);
                $prefix = $filename[1];//后缀名，用户传过来的值，不准确，不安全
                //----获取略去后缀名的文件名结束----//
                $new_filename=md5(getRandomString('32').$filename);
                $path = "upload/" . date("Y-m-d", time());
                if(!file_exists($path)){
                    mkdir($path);
                }
                $upload_pathName = 'alipayerweima';
				
                //4.保存数据
                //保存上传文件
//                注意：如果没有 ROOT全路径的话,就会上传失败，切记。
//                正确写全路径
//                $move_path=str_replace('\\','/',WY_ROOT."/".$path ."/". $new_filename.".".$prefix);//使用阿里云对象存储 OSS
//                move_uploaded_file($file_tmp, $move_path);//使用阿里云对象存储 OSS
                //使用阿里云对象存储 OSS开始
                require_once WY_ROOT."/api/aliyun-oss-php-sdk-master/autoload.php";
                $ossClient = new OSS\OssClient("LTAI4vCVM93Qnkln", "hmq4NVZD76W2gLkiUSOeJVxsb3YQ1k", "http://oss-cn-shanghai.aliyuncs.com");
                $result = $ossClient->uploadFile("957ka", "upload/".$upload_pathName."/".date("Y-m-d", time())."/".$new_filename . "." . $prefix, $file['tmp_name']);
                $erweima = $result['oss-request-url'];
				$_return = array();
                $_return['status'] = 1;
                $_return['imgpath'] =$erweima;
				echo json_encode($_return);
                exit;
               
            }
            if($do_action == 'wechat.material') {
                //保存素材
                $_where = $_data = array();
                $_data =  $_REQUEST;
                if($_data['MaterialType'] == 0) {
                    //单素材
                    if($_data['ImgPath']) {
                        $_data['title_pic_url'] = $_data['ImgPath'];
                    } else {
                        unset($_data['title_pic_url']);
                    }
                    if(!empty($_data['MId'])) {
                        $_where['id'] = $_data['MId'];
						unset($_data['MId']);
						$ob->insert("material",$_data,"id=".$_data['MId']);
                    } else {
                        $_data['time_add'] = time();
						unset($_data['FileUpload']);
						unset($_data['ImgPath']);
						unset($_data['submit_button']);
						unset($_data['MaterialType']);
						unset($_data['do_action']);
						unset($_data['d']);
						unset($_data['type']);
						unset($_data['action']);
						$ob->insert("material",$_data);
                    }
                } else {
                    //多素材
                    $_data['time_add'] = time();
                    $_parent_id = 0;
					unset($_data['action']);
                    foreach ($_data['Title'] as $k => $v) {
                        if(empty($v)) {
                            continue;
                        }
                        $_dataSub = array();
                        $_dataSub['title'] = $v;
                        $_dataSub['link_url_id'] = $_data['Url'][$k];
                        if($_data['ImgPath'][$k]) {
                            $_dataSub['title_pic_url'] = $_data['ImgPath'][$k];
                        } else {
                            unset($_dataSub['title_pic_url']);
                        }
                        if($k == 0) {
                            $_dataSub['parent_id'] = 0;
                        } else {
                            $_dataSub['parent_id'] = $_parent_id;
                        }
                        if($_data['MId']) {
                            if(empty($_data['subid'][$k])) {
                                $_dataSub['time_add'] = $_data['time_add'];
                                $_dataSub['parent_id'] = $_data['MId'];
                                $M_WxMaterial->insert("material",$_dataSub);
                            } else {
                                $_where = array();
                                unset($_dataSub['parent_id']);
                                $_where['id'] = $_data['subid'][$k];
                                $ob->update("material",$_dataSub,"id=".$_data['subid'][$k]);
                            }
                        } else {
                            $_dataSub['time_add'] = $_data['time_add'];
                            $_id = $ob->insert("material",$_dataSub);
                            if($k == 0) {
                                $_parent_id = $_id;
                            }
                        } //end if
                    } 
					//end foreach
                } //end if
			    Redirect('/empress/wechart.php?action=material');
                exit;
            }
        } // end if $this->isPost()
        //修改的id
		
        $id =$_REQUEST['id'];
	
        if($id) {
			
            $resInfo= $ob->fetch_one('weixin_config','id='.$id,'*');
            if($type == 1) {
                $_where = array();
                $_where['parent_id'] = $resInfo['id'];
                $_order = array('id' => 'ASC');
                $resInfo['resSub'] =$ob->fetch_all('material',$limit,$offset,"parent_id=".$resInfo['id'],'order by id asc'); 
            }
        }
        //删除
    
        if($do_action == 'wechat.material_del' && $id) {
            //删除子类
            $ob->delete('material',"parent_id=".$id);
            //删除自己
            $ob->delete('material',"id=".$id);
        } else if($do_action == 'material.material_multi_del') {
            //删除多图文里的单个图文信息
            $subid = $_REQUEST['subid'];
			$ob->delete('material',"id=".$subid);
            exit;
        }
		$_strTemplate = '';
		if($d == 'add') {
			    $_strTemplate="materialadd";
			if($type == 1) {
				$_strTemplate="materialadd1";
			}
		} else {
            //取出所有记录
			$page = _G('p', 'int');
            $page = $page == false ? 1 : $page;
			$pl=($page-1)*15;
			
			$resLists = $ob->fetch_all('material',$pl.",15",$offset,"parent_id=0",'order by id desc'); 
		
            foreach($resLists  as $k => $v) {
                $resLists[$k]['resSub'] = $ob->fetch_all('material',$limit,$offset,"parent_id=".$v['id'],'order by id asc'); 	
            }
			
			$_strTemplate="material";
        }
	
    //返回链接
	
    $resUrl= $ob->getSelectHtml(1, '');
    require View::getView('header');
    require View::getView($_strTemplate);
    require View::getView('footer');

    View::Output();
}


//微信接口配置

if ($action =='option_url') {

	$do_action = $_REQUEST['do_action'];
		$p = $_GET["page"];
		if(!$p){
			$p=1;
		}
        if($_POST) {
            if($do_action == 'wechat.url') {
                $_where = $_data = array();
                $_data = $_POST;
				unset($_data['do_action']);
				unset($_data['action']);
			
                if($_data['link_url']) {
                    preg_match('/^http/i', $_data['link_url'], $match);
                    if(empty($match)) {
                        $_data['link_url'] = 'http://' . $_data['link_url'];
                    }
                }
                if($_data['id']) {
					$ob->update('materialurl',$_data,'id='.$_data['id']); 	
                } else {
					unset($_data['id']);
                    $_data['time_add'] = time();
                    $ob->insert('materialurl',$_data); 
                }
                Redirect('/empress/wechart.php?action=option_url');
                exit;
            }
        }
        //修改的id
        $id = $_GET["id"];
        if($id) {
            $resInfo =$ob->fetch_one('materialurl','id='.$id); 
			
        }else{
			 $resInfo['link_name']="";
			 $resInfo['link_url']="";
			 $resInfo['id']="";
		}
        if($do_action == 'wechat.url_del' && $id) {
			$ob->delete('materialurl','id='.$id);
        }
        //取出列表
		$pg=($p-1)*15;
        $resUrl = $ob->fetch_all('materialurl',$pg.",15",$offset,$cons,'order by id asc'); 

    require View::getView('header');

    require View::getView('option_url');

    require View::getView('footer');

    View::Output();

}

?>